package com.meihua.workflow.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.meihua.workflow.constants.R;
import com.meihua.workflow.global.GlobalFilter;
import com.meihua.workflow.model.Contract;
import com.meihua.workflow.model.ProcessInstanceTemplate;
import com.meihua.workflow.model.SysUser;
import com.meihua.workflow.model.TaskTemplate;
import com.meihua.workflow.service.ContractService;
import com.meihua.workflow.service.SysUserService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author MaHeqiang
 */
@RestController
@RequestMapping("/process")
public class ProcessInstanceController {
    @Resource
    private SysUserService sysUserService;
    @Resource
    private ContractService contractService;
    @GetMapping("/start")
    public R startProcessInstance(@RequestParam("contractNum") String contractNum){
        LambdaQueryWrapper<Contract> contractLambdaQueryWrapper = new LambdaQueryWrapper<>();
        contractLambdaQueryWrapper.eq(Contract::getContractNum,contractNum);
        Contract one = this.contractService.getOne(contractLambdaQueryWrapper);
        if (BeanUtil.isEmpty(one)){
            return R.error("查询不到该合同");
        }
//    public R startProcessInstance(@PathVariable(value = "type") String type, @PathVariable(value = "num") String num) {
        SysUser sysUser = this.sysUserService.getById(GlobalFilter.getUserId);
        // 1. 创建ProcessEngine
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        // 2. 获取RuntimeService
        RuntimeService runtimeService = processEngine.getRuntimeService();
        Map map = new HashMap<String, Object>();
        map.put("assignee1", sysUser.getName());
        map.put("assignee2", "审批人2");
        map.put("assignee3", "审批人3");
        map.put("assignee4", "审批人4");
        map.put("assignee5", "审批人5");
        map.put("assignee6", "审批人6");
        map.put("isPassed", 0);
        map.put("num",one.getAmount());
        map.put("type",one.getServiceType());
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("合同审批流模型", map);
        System.out.println("--------审批流创建成功--------------");
        System.out.println("流程实例id：" + processInstance.getProcessInstanceId());
        System.out.println("流程实例名称：" + processInstance.getName());
        return R.success("创建成功" + processInstance.getProcessInstanceId());
    }

    //查询审批是否结束
    @GetMapping("/{processInstanceId}")
    public R processInstanceIsFinished(@PathVariable("processInstanceId") String processInstanceId) {
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        HistoryService historyService = processEngine.getHistoryService();
        HistoricProcessInstance historicProcessInstance = historyService
                .createHistoricProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        if (historicProcessInstance == null) {
            return R.error("流程不存在");
        }
        if (historicProcessInstance.getEndTime() == null) {
            return R.error("流程未结束！");
        }
        return R.success("流程已结束！");
    }

    @DeleteMapping("/{processInstanceId}")
//    删除个人任务
    public R deleteProcessInstance(@PathVariable("processInstanceId") String processInstanceId) {
        String endReason = "用户主动结束";
        RuntimeService runtimeService = ProcessEngines.getDefaultProcessEngine().getRuntimeService();
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId)
                .singleResult();
        if (processInstance == null) {
            return R.error("流程不存在！");
        }
        runtimeService.deleteProcessInstance(processInstance.getId(), endReason);

        return R.success("流程删除成功！"+endReason);
    }

    //查看审批进度
    @GetMapping("/{processInstanceId}/p")
    public R selectApproveProcess(@PathVariable("processInstanceId") String processInstanceId){
        // 历史节点
        HistoryService historyService = ProcessEngines.getDefaultProcessEngine().getHistoryService();
        List<HistoricActivityInstance> list = historyService
                .createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceEndTime()
                .asc()
                .finished()
                .list()
                .stream()
                .filter(item -> !StringUtils.containsAny(item.getActivityType(), "inclusiveGateway", "parallelGateway","exclusiveGateway"))
                .collect(Collectors.toList());
        List<TaskTemplate> taskTemplates = new ArrayList<>();
        // 历史变量

        for (int i = 0; i < list.size(); i++) {
            TaskTemplate taskTemplate = new TaskTemplate();
//            System.out.println("========");
            HistoricActivityInstance historicActivityInstance = list.get(i);
//            System.out.println(historicActivityInstance.getActivityName());
            String taskId = historicActivityInstance.getTaskId();
            String assignee = historicActivityInstance.getAssignee();
//            System.out.println(assignee);
//            System.out.println(taskId);
//            String result = "";
//            if (StringUtils.isNotEmpty(taskId)) {
//                HistoricVariableInstance historicVariableInstance = historyService.createHistoricVariableInstanceQuery().taskId(taskId).variableName("num").singleResult();
//                System.out.println("测试：：：："+historicVariableInstance);
//                result = historicVariableInstance.getValue().toString();
//                // 已经经过的节点不适用该方法查询变量
////                result = (String) taskService.getVariableLocal(taskId, "result");
//            }
//            System.out.println(historicActivityInstance.getAssignee() + "----" + result);
//            System.out.println(historicActivityInstance.getStartTime());
//            System.out.println(historicActivityInstance.getEndTime());
            taskTemplate.setTaskId(taskId);
            taskTemplate.setTaskName(historicActivityInstance.getActivityName());
            taskTemplate.setTaskAssignee(assignee);
            taskTemplate.setTaskStartTime(historicActivityInstance.getStartTime());
            taskTemplate.setTaskEndTime(historicActivityInstance.getEndTime());
            taskTemplates.add(taskTemplate);
        }
    return R.success(taskTemplates);
    }
}

